package com.zjdiepu.www.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.zjdiepu.www.common.consts.SystemConsts;
/**
 * 项目名称 dpqc-parent-manager-common <br/> 
 * 类名称 HttpUtil <br/>  
 * 类描述 http请求相关工具<br/>    
 * 创建人 xiongxiaotun <br/> 
 * 创建时间 2017年4月8日 上午9:54:01  <br/>   
 * 修改人 xiongxiaotun <br/> 
 * 修改时间 2017年4月8日 上午9:54:01   <br/>  
 * 修改备注   <br/> 
 * @version V1.0   <br/>
 */
public class HttpUtil {
	/**
	 * @author xiongxiaotun <br/>
	 * @Title isAjaxRequest  <br/>
	 * @Description 判断是否是异步请求 <br/>
	 * @param request
	 * @return
	 * @version V1.0  <br/>
	 */
    public static boolean isAjax(ServletRequest request) {
    	if(!(request instanceof ServletRequest)) {
    		return false;
    	}
    	HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        String requestedWith = httpServletRequest.getHeader("x-requested-with");
        String contentType = httpServletRequest.getHeader("Content-Type");
        String mobileFlag = httpServletRequest.getHeader(SystemConsts.MOBILE_FLAG);
        
        return "XMLHttpRequest".equalsIgnoreCase(requestedWith) || "application/json".equals(contentType) 
        		|| "ios".equals(mobileFlag) || "android".equals(mobileFlag) || "tablet".equals(mobileFlag);
    }
    
    /**
	 * @author xiongxiaotun <br/>
	 * @Title printResponse  <br/>
	 * @Description 输出字符到前端 <br/>
	 * @param response
	 * @param jsonString
	 * @version V1.0  <br/>
	 * @throws IOException 
	 */
	public static void printResponse(ServletResponse response, Object result) throws IOException {
		if(!(response instanceof HttpServletResponse)) {
			return;
		}
		if(null == result) {
			return;
		}
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		httpServletResponse.reset();
		httpServletResponse.setContentType("application/json;charset=UTF-8");
		httpServletResponse.setCharacterEncoding("UTF-8");
		PrintWriter out = httpServletResponse.getWriter();
		out.println(JSON.toJSONString(result));
		out.flush();
		out.close();
	}
}
